package com.jiangore.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 *
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    public static final Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {

    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }

    /**
     * 插入时
     * 表公共字段为空自动填充
     */
   /* public void insertFill(MetaObject metaObject) {
        log.info("insert ...");

        //获取当前登录用户
        Admin admin = MyMetaObjectHandler.getAdmin();

        Integer uid = 1;
        if (admin != null) {
            uid = admin.getId();
        }

        //这些字段需要在BaseEntity里字段上加注解
        Object createUser = getFieldValByName("createUser", metaObject);
        Object createTime = getFieldValByName("createTime", metaObject);
        Object updateUser = getFieldValByName("updateUser", metaObject);
        Object updateTime = getFieldValByName("updateTime", metaObject);

        if (null == createUser) {
            metaObject.setValue("createUser", uid);
        }
        if (null == createTime) {
            metaObject.setValue("createTime", LocalDateTime.now());
        }
        if (null == updateUser) {
            metaObject.setValue("updateUser", uid);
        }
        if (null == updateTime) {
            metaObject.setValue("updateTime", LocalDateTime.now());
        }
    }*/

    /**
     * 更新时
     * 表公共字段为空自动填充
     */
    /*@Override
    public void updateFill(MetaObject metaObject) {
        log.info("update ...");

        Admin admin = MyMetaObjectHandler.getAdmin();

        Integer uid = 1;
        if (admin != null) {
            uid = admin.getId();
        }

        Object updateUser = getFieldValByName("updateUser", metaObject);
        Object updateTime = getFieldValByName("updateTime", metaObject);

        if (null == updateUser) {
            metaObject.setValue("updateUser", uid);
        }
        if (null == updateTime) {
            metaObject.setValue("updateTime", LocalDateTime.now());
        }
    }*/

    /**
     * 获取session中的管理员
     * @return Admin
     */
    /*private static Admin getAdmin() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attrs.getRequest();
        HttpSession session = req.getSession();
        Admin admin = (Admin)session.getAttribute("admin");
        return admin;
    }*/

}
